package com.springdoor.wx.config.manager.factory;

import com.springdoor.wx.log.entity.WxLogininfor;
import com.springdoor.wx.log.entity.WxOperLog;
import com.springdoor.wx.log.service.WxLogininforService;
import com.springdoor.wx.constant.Constants;
import com.springdoor.wx.log.service.WxOperLogService;
import com.springdoor.wx.utils.ServletUtils;
import com.springdoor.wx.utils.ip.AddressUtils;
import com.springdoor.wx.utils.string.LogUtils;
import com.springdoor.wx.utils.string.StringUtils;
import com.springdoor.wx.utils.spring.SpringUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 * 
 * @author ruoyi
 */
public class AsyncFactory
{
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 记录登录信息
     * 
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @param args 列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(
            final String userId, final String username, final String ip, final String address
            , final String status, final String message, final Object... args)
    {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        return new TimerTask()
        {
            @Override
            public void run()
            {
                try {
                    StringBuilder s = new StringBuilder();
                    s.append(LogUtils.getBlock(ip));
                    s.append(address);
                    s.append(LogUtils.getBlock(username));
                    s.append(LogUtils.getBlock(status));
                    s.append(LogUtils.getBlock(message));
                    // 打印信息到日志
                    sys_user_logger.info(s.toString(), args);
                    // 获取客户端操作系统
                    String os = userAgent.getOperatingSystem().getName();
                    // 获取客户端浏览器
                    String browser = userAgent.getBrowser().getName();
                    // 封装对象
                    WxLogininfor logininfor = new WxLogininfor();
                    logininfor.setUserId(userId);
                    logininfor.setUserName(username);
                    logininfor.setIpaddr(ip);
                    logininfor.setLocation(address);
                    logininfor.setBrowser(browser);
                    logininfor.setOs(os);
                    logininfor.setMsg(StringUtils.substring(message, 0, 250));
                    // 日志状态
                    if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
                    {
                        logininfor.setStatus(Constants.SUCCESS);
                    }
                    else if (Constants.LOGIN_FAIL.equals(status))
                    {
                        logininfor.setStatus(Constants.FAIL);
                    }
                    // 插入数据
                    SpringUtils.getBean(WxLogininforService.class).insertWxLogininfor(logininfor);
                } catch (Exception e) {
                    sys_user_logger.info(ExceptionUtils.getMessage(e));
                    sys_user_logger.error(ExceptionUtils.getMessage(e));
                }
            }
        };
    }

    /**
     * 操作日志记录
     * 
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final WxOperLog operLog)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(WxOperLogService.class).insertWxOperLog(operLog);
            }
        };
    }
}
